<?php

namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\SoftDeletes;
use Str;
use App\Models\Traits\GoodsHandler;



class Goods extends Model
{
    use SoftDeletes,GoodsHandler;

    protected $fillable = [
        'goods_name','price','goods_code','goods_img'
    ];

    protected $dates = ['deleted_at'];


    public function user()
    {
        return $this->belongsTo(User::class , 'user_id' , 'id');
    }


    // 指定商品浏览数据表 方法。
    public function getOneGoodsBrowse(){

        return $this->user->userBrowseTotal->where('goods_id' , $this->id);
    }


    // 关联 goodsBrowse 表
    public function goodsBrowse()
    {
        return $this->hasMany(GoodsBrowse::class , 'goods_id' , 'id');
    }


    // 关联 UserBrowseTotal 表
    public function userBrowseTotal()
    {
        return $this->hasMany(UserBrowseTotal::class , 'goods_id' , 'id');
    }


    /**
     * userBrowseTotal 表，浏览数据合并计算
     */
    public function sumBrowseTotal($exclude = '')
    {
        return $this->with(['userBrowseTotal'=>function($query) use ($exclude){
            $query->select([
                'user_id','goods_id',
                \DB::raw('SUM(pagevies) as pagevies'),
                \DB::raw('SUM(show_num) as show_num'),
                \DB::raw('SUM(order_num) as order_num'),
                \DB::raw('SUM(deal_num) as deal_num'),
            ])->groupBy(['user_id','goods_id']);
            $query->when(isset($exclude['created_at']) , function($q2) use ($exclude){
                list($t1 , $t2) = explode('/' , $exclude['created_at']);
                $q2->whereBetween('created_at',[Carbon::parse($t1) , Carbon::parse($t2)]);
            });
        }]);
    }


    public function setGoodsCodeAttribute(){

        if (empty(request()->goods_code)){

            $this->attributes['goods_code'] = Str::random(18);
        }
    }





    //
}
